<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/12/26
 * Time: 16:07
 */

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class AdminMenu extends Model
{
            protected $table = 'admin_menu';
            protected $primaryKey = 'id';
            protected $guarded=[];
            protected $fillable = [''];

            /**
             * 递归获取菜单
             *
             * @param $name
             * @param $collection
             * @param string $parentId
             * @param null $item
             * @return array
             */
            public function getDepartments(&$collection, $parentId = '0', &$item = null, $name = 'children')
            {
                $tree = [];
                foreach ($collection as $key => $value) {
                    if ($value['parent_id'] == $parentId) {
                        self::shiftCollection($collection, $value, $key);
                        if ($item) $item[$name][] = $value;
                        else $tree[] = $value;
                    }
                };
                return $tree;
            }
            /**
             * 删除已分配的元素(可减少循环, 减少内存占用)
             *
             * @param $key
             * @param $collection
             * @param $value
             */
            public function shiftCollection(&$collection, &$value, $key)
            {
                unset($collection[$key]);
                self::getDepartments($collection, $value['id'], $value);
            }
}

